import Taro, {useDidShow, useLoad} from "@tarojs/taro";
import {Image, Text, View} from "@tarojs/components";
import { useState } from 'react';
import './css/MainContent.css';
import MapPin from './svg/map-pin.svg';
import Users from "./svg/users.svg";
import TrendingUp from "./svg/trending-up.svg";
import categoryMap from '../util/categoryMapping';
import {getRequest} from '../util/request'

export default function MainContent() {

  const [trainList, setTrainList] = useState<any>([]);
  const [sortType, setSortType] = useState<boolean>(true);

  const gotoPage = (id) => {
    Taro.navigateTo({url: `/pages/traindetail/index?trainId=${id}`});
  }

  const queryList = () => {
    getRequest('/bsTrain/list',  res=> {
      setTrainList(res.data.map(item => {
        return {
          id: item.id,
          title: item.title,
          location: item.place,
          date: item.startDate,
          views: item.views,
          category: item.category,
          categoryName: categoryMap[item.category],
          participants: item.participants,
          image: item.cover,
          tags: item.tags?item.tags.split(',').filter(t => t !== ''):[],
        }
      }).sort((a, b) => {
        return sortType ? b.views - a.views : a.views - b.views
      }))
    })
  }

  useLoad(() => {
    queryList()
  })

  useDidShow(() => {
    queryList()
  })

  const sortList = () => {
    setSortType(!sortType)
    setTrainList(trainList.sort((a, b) => {
      return !sortType ? b.views - a.views : a.views - b.views
    }))
  }

  return (
    <View className='top-container'>
      <View>
        <View className='hots' onClick={()=>{sortList()}}>
          <Image className='map-pin' src={TrendingUp} />
          <Text className='trending-text'>热度 {sortType ? '↓' : '↑'}</Text>
        </View>
      </View>
      <View className='list-container'>
        {trainList.map((card, index) => (
          <View className='card' key={index} onClick={() => gotoPage(card.id)}>
            <Image className='card-image' src={card.image} />
            <View className='card-title'>{card.title}</View>
            <View className='card-description'>
              <Image src={MapPin} className='map-pin' />
              <Text className='category-text'>{card.location}</Text>
              <View className='date'>{card.date}</View>
            </View>
            <View className='category'>{card.categoryName}</View>
            <View className='persons'><Image src={Users} className='avatar1' />{card.participants}</View>
            <View className='views'>{card.views}浏览</View>
            <View className='m-tagview'>
              {card.tags.map(tag => (<View key={tag} className='m-tags'>{tag}</View>))}
            </View>
          </View>
        ))}
      </View>
      <View className='page-bottom'></View>
    </View>
  );
}
